//
//  RecommendViewController.m
//  GOGOTravel
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 果果. All rights reserved.
//

#import "RecommendViewController.h"
#import "DailyFeatureStoryViewController.h"
#import "GameViewController.h"
#import "type12ViewController.h"
#import "SearchMuniTableViewCell.h"
#import "SearchCollectionViewCell.h"
#import "HGCollectionReusableView.h"
#import "DBsearchModel.h"
#import "NSString+ URL.h"
#import "SearchResultDisplayViewController.h"
#import "CityViewController.h"
#import "GiFHUD.h"
#import "SanFangDengLuViewController.h"
#import "UMSocial.h"
#import "FuJinViewController.h"
#import "DailyTableViewCell.h"

@interface RecommendViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, DailyFeatureTableViewCellDelegate, UISearchBarDelegate, UICollectionViewDelegateFlowLayout, MAMapViewDelegate, AMapSearchDelegate,UMSocialUIDelegate, DailyTableViewCellDelegate>


{
    MAMapView *_mapView;
    CLLocation *_currentLocation;
    AMapSearchAPI *_search;
    NSArray *_pois;
    
    NSMutableArray *_annotations;
}

@property (nonatomic, assign) BOOL isWifi;

@property (nonatomic, retain) Reachability *conn; // 检查网络状态对象;
@property (nonatomic, copy) NSString *urlResult;/**<  搜索结果数据网址 */
@property (nonatomic, retain) BaseCollectionView *collection;
@property (nonatomic, retain) UITableView *TableView; /**<  推荐页tableView */
@property (nonatomic, retain) NSMutableArray *searchoutCountrYArr;/**<  搜索数组 */

@property (nonatomic, retain) NSMutableArray *dataArr;/**<  数据数组 */

@property (nonatomic, retain) NSMutableArray *DailyArr;/**<  每日精选数组 */

@property (nonatomic, retain) NSMutableArray *BannerArr;/**<  广告数组 */

@property (nonatomic, retain) UIScrollView *scroll; /** 广告视图 */

@property (nonatomic, retain) UIPageControl *page;/**<  页面控制器 */

@property (nonatomic, assign) NSInteger i; /**<  滚动视图计数 */
@property (nonatomic, retain) UIView *view1;

@property (nonatomic, retain) NSTimer *timer; /** 定时器 */

//时间间隔
@property (nonatomic,assign)NSTimeInterval duration;

//当前下标
@property (nonatomic,assign)NSUInteger currentIndex;

@property (nonatomic, retain) ExperienceDetailsViewController *exprience;/**<  push页面对象 */


@property (nonatomic, retain) NSMutableArray *searchInCountryArr;/**<  装searchmodel的数组 */

@property (nonatomic, retain) NSMutableArray *dailyStoryArr;/**< 故事精选 */
@property (nonatomic, retain) UISearchController *searchController;/**<  搜索控制器 */
@property (nonatomic, retain) UISearchBar *searchBar;/**<  声明属性 */
@property (nonatomic, assign) BOOL isHeader;
@property (nonatomic, copy) NSString *page11;
@property (nonatomic, copy) NSString *resultUrl;/**<  拼接后的网址字符串 */

@property (nonatomic, retain) UIView *SearchView;/**<  搜索下拉view */
@property (nonatomic, retain) UITableView *searchTableView;
@property (nonatomic, retain) UIBarButtonItem *item;/**<  附近按钮 */
@property (nonatomic, retain) UIView *ViewSearchBar;/**<  放searchBar的view */
@property (nonatomic, retain) UIBarButtonItem *itemCancle;/** 右边取消按钮 */
@property (nonatomic, retain) UICollectionView *searchCollection;/**<  搜索界面的collectionview */

@property (nonatomic, copy) NSString *searchTeatID;/**<  搜索text的全局量 */

@property (nonatomic, retain) NSMutableArray *DataBaseArr;/**<  存放搜索的数组 */
@property (nonatomic, retain) NSMutableDictionary *location;/**<  装经纬度的字典 */

@end

@implementation RecommendViewController

- (void)dealloc{
    [_conn release];
    [_page11 release];
    [_collection release];
    [_dailyStoryArr release];
    [_TableView release];
    [_searchoutCountrYArr release];
    [_searchInCountryArr release];
    [_BannerArr release];
    [_DailyArr release];
    [_scroll release];
    [_dataArr release];
    [_searchController release];
    [_searchBar release];
    [_SearchView release];
    [_page release];
    [_searchTableView release];
    [_resultUrl release];
    [_ViewSearchBar release];
    [_itemCancle release];
    [_item release];
    [_DataBaseArr release];
    [_searchTeatID release];
    [_location release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.location = [NSMutableDictionary dictionary];
    }
    return self;
}

#pragma mark-定位
- (void)initMapView {
    [MAMapServices sharedServices].apiKey = APIKey;
    
    _mapView = [[MAMapView alloc] init];
    _mapView.delegate = self;
    
    // 打开定位功能
    _mapView.showsUserLocation = YES;
    

}

//获取当前用户经纬度:使用mapView的回调方法
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    NSLog(@"userLocation: %@", userLocation.location);
        
        NSString *str = [NSString stringWithFormat:@"%@", userLocation.location];
        if (str.length > 13) {
            NSString * str1= [str substringWithRange:NSMakeRange(1, 12)];
            NSString *str2 = [str substringWithRange:NSMakeRange(14, 13)];
            NSLog(@"%@ %@", str1, str2);
            
            
            [_location setValue:str1 forKey:@"lat"];
            [_location setValue:str2 forKey:@"lng"];
            
            _currentLocation = [userLocation.location copy];
            
    }
      
    
}

// 逆地理编码
// 发起搜索请求
- (void)reGeoAction
{
    if (_currentLocation)
    {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
        [_search AMapReGoecodeSearch:request];
    }
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:
(AMapReGeocodeSearchResponse *)response
{
    //NSLog(@"response :%@", response);
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0)
    {
        title = response.regeocode.addressComponent.province;
    }
    _mapView.userLocation.title = title;
    _mapView.userLocation.subtitle = response.regeocode.formattedAddress;
}

// 在选中用户位置annotation时弹出当前地址
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        [self reGeoAction];
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        annotationView.canShowCallout = YES;
        return annotationView;
    }
    return nil;
}

- (void)viewWillDisappear:(BOOL)animated{
    [_searchBar setHidden:YES];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [_searchBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.9 green:0.29 blue:0.44 alpha:1];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.translucent = NO;
     [self initMapView];
    
    //检测网络
    self.conn = [Reachability reachabilityForInternetConnection];
    // 让Reachability开启被监听状态
    [self.conn startNotifier];
    [self checkNetWorkState];
    
    
    [self initrecommendTableView];
    
    [GiFHUD setGifWithImageName:@"b879f2e742d94b2a8f2362d0ca7e18c7.gif"];
    [GiFHUD show];
    [self handleData];
    
    [self initeHeaderreflech];
    [self initFootreflech];
    //附近按钮
    [self initButton];
    
    [self initSearch];
    
    _duration = 3;
   
    //创建下滑的scrollview
    [self createSearchView];
    
}

/**<  创建下拉刷新 */
- (void)initeHeaderreflech{
    
    [_TableView addHeaderWithCallback:^{

        _isHeader = YES;
        [self handleData];
    }];
}

- (void)initFootreflech{
    
    [_TableView addFooterWithCallback:^{
        NSString *str =@"http://api.breadtrip.com/v2/index/?next_start=2387112872&sign=9d59af4bd99c8bd41419f5be1479ddb5";
        _resultUrl = [str stringByReplacingCharactersInRange:NSMakeRange(46, 10) withString:_page11];
      
        _isHeader = NO;
        [self handleDataFoot];
    }];
    
}

/** 创建附近按钮 */
- (void)initButton{
    self.item = [[UIBarButtonItem alloc] initWithTitle:@"附近" style:UIBarButtonItemStylePlain target:self action:@selector(itemAction:)];
    
    self.navigationItem.rightBarButtonItem = _item;
    [_item release];
    }
/**<  附近button点击方法 */
- (void)itemAction:(UIBarButtonItem *)item{
    NSLog(@"附近");
    FuJinViewController *fujin = [[FuJinViewController alloc] init];
    fujin.location = _location;
    [self.navigationController pushViewController:fujin animated:YES];
    
    [fujin release];
}

#pragma mark- UISearch
/** UISearch */
- (void)initSearch{
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(3, 3, self.view.frame.size.width - 95, 35)];
    
    _searchBar.placeholder = @"搜索目的地,游记,故事集,用户";
    _searchBar.delegate = self;
    
    [self.navigationController.navigationBar addSubview: _searchBar];
    
    [_searchBar release];
    
}
/**<  创建右边取消按钮 */
- (void)createCancleButton{
    self.itemCancle = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(itemCancle:)];
    self.navigationItem.rightBarButtonItem = _itemCancle;
    [_itemCancle release];
}
/**<  取消按钮的方法 */
- (void)itemCancle:(UIBarButtonItem *)item{
    _searchBar.text = @"";
    
    //取消第一响应
    [_searchBar resignFirstResponder];
    //删除原有的右边item
    self.navigationItem.rightBarButtonItem = nil;
    //将附近赋给右边item
    self.navigationItem.rightBarButtonItem = _item;
    
    //乡下滑动到动画
    [UIView animateWithDuration:0.2 animations:^{
        _SearchView.frame = CGRectMake(0, -self.view.frame.size.height-100, self.view.frame.size.width, self.view.frame.size.height);
    }];
    //让tabbar取消隐藏
    [self.tabBarController.tabBar setHidden:NO];
}
#pragma mark-searchBar的代理方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{

    
    self.navigationItem.rightBarButtonItem = nil;
    [self createCancleButton];
    //乡下滑动到动画
    [UIView animateWithDuration:0.2 animations:^{
        _SearchView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
    
    //让tabbar隐藏
    [self.tabBarController.tabBar setHidden:YES];
    return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    self.searchTeatID = searchText;
    
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
             //创建一个model对象
            DBsearchModel *model = [DBsearchModel dbSearchText];
            //将搜索text的转化成属性
            [model setValue:_searchTeatID forKey:@"searchText"];
            //插入到数据库中
            [[DbHandel shareDbHandel] insertModel:model];
            
             [_DataBaseArr addObject:model];
    
    
            [_searchCollection reloadData];
            
             //处理搜索数据
    
    [self handleSearchResultData];
    
    
    
    SearchResultDisplayViewController *searchResult = [[SearchResultDisplayViewController alloc] init];
    
    searchResult.url = _urlResult;
    //跳转到另一个界面
    [self.navigationController pushViewController:searchResult animated:YES];
    [searchResult release];
    
   
}


/** 创建搜索下拉view */
- (void)createSearchView{

    //查询数据库
    self.DataBaseArr = [[DbHandel shareDbHandel] selectTable];
    
    
    self.SearchView = [[UIView alloc] init];
    
    _SearchView.frame = CGRectMake(0, -self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height);
    _SearchView.backgroundColor = UIColorFromRGB(0xFFF0F5);
    [self.view addSubview:_SearchView];
    [_SearchView release];
    
    UICollectionViewFlowLayout * layout= [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake((300 - 4)/3, 30);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerReferenceSize = CGSizeMake(_searchCollection.frame.size.width, 60);
    
    self.searchCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width - 20, self.view.frame.size.height-90) collectionViewLayout:layout];
    _searchCollection.delegate = self;
    _searchCollection.dataSource = self;
    _searchCollection.backgroundColor = [UIColor clearColor];
    [_SearchView addSubview:_searchCollection];
    [_searchCollection release];
    
    
    
    [_searchCollection registerClass:[SearchCollectionViewCell class] forCellWithReuseIdentifier:@"SearchCollectionViewCell"];
    
    [_searchCollection registerClass:[HGCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HGCollectionReusableView"];
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //取消searchBar的第一响应
    [_searchBar resignFirstResponder];
    
}

/** 完成协议内容跳转页面 */
- (void)tapButtonJump{
    DailyStoryViewController *daily = [[DailyStoryViewController alloc] init];
    
    [self.navigationController pushViewController:daily animated:YES];
}

/** 创建tableView */

- (void)initrecommendTableView{
    
    self.TableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
    
    _TableView.delegate = self;
    _TableView.dataSource = self;
    _TableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    [self.view addSubview:_TableView];
    [_TableView release];
     //注册
    [_TableView registerClass:[DailyTableViewCell class] forCellReuseIdentifier:@"DailyTableViewCell"];
    //注册推荐产品的cell
    [_TableView registerNib:[UINib nibWithNibName:@"RecommendProductTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"RecommendProductTableViewCell"];
    //注册热门游记的cell
  [_TableView registerNib:[UINib nibWithNibName:@"HotPlaceTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"HotPlaceTableViewCell"];
    //注册每日精选的cell
    [_TableView registerNib:[UINib nibWithNibName:@"DailyFeatureTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"DailyFeatureTableViewCell"];
    //注册
    [_TableView registerNib:[UINib nibWithNibName:@"RecommendLogoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"RecommendLogoTableViewCell"];
    
}
//创建轮播图
- (void)initBanner{
    
    NSMutableArray *arr = [NSMutableArray array];
    
    for (Banner *model in _BannerArr) {
        NSString *strr = model.image_url;
        [arr addObject:strr];
    }
    
    DCPicScrollView *dc = [DCPicScrollView picScrollViewWithFrame:CGRectMake(0, 0, WIDTH, 200) WithImageUrls:arr];
    
    dc.placeImage = [UIImage imageNamed:PLACE_HLODER];
    dc.AutoScrollDelay = 2;
    
    [_view1 addSubview:dc];
    
    [[DCWebImageManager shareManager] setDownloadImageRepeatCount:1];
    [[DCWebImageManager shareManager] setDownLoadImageError:^(NSError *error, NSString *string) {
        NSLog(@"%@", error);
    }];
    //点击方法
    [dc setImageViewDidTapAtIndex:^(NSInteger index) {
        
        ExperienceDetailsViewController *ex = [[ExperienceDetailsViewController alloc] init];
        
        Banner *model = _BannerArr[index];
        
        ex.url = model.html_url;
        
        [self.navigationController pushViewController:ex animated:YES];
        
        NSLog(@"%ld", (long)index);
    }];
    
    
}

#pragma mark- 创建COLLECTIONvIEW

#pragma mark- collectionView代理方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (collectionView == _collection) {
        return 1;
    }else{
        return 3;
        
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    
    if (collectionView == _collection) {
        
    }else{
        if (UICollectionElementKindSectionHeader == kind) {
            HGCollectionReusableView *hearder = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HGCollectionReusableView" forIndexPath:indexPath];
            
            if (indexPath.section == 0) {
                hearder.label.text = @"搜索历史";
            }else if (indexPath.section == 1){
                hearder.label.text = @"国外热门城市";
            }else{
                hearder.label.text = @"国内热门城市";
            }
            
            return hearder;
        }
        
    }
    
    
    
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (collectionView == _searchCollection) {
        return CGSizeMake(_searchCollection.frame.size.width, 60);
    }else{
        return CGSizeZero;
    }
    
}

/** 跳转页面到每日精选详情 */

- (void)jumpToDailyVcWithShouChangModel:(ShouChangModel *)model model:(Daily *)dailyModel string:(NSString *)url{
    
    DailyFeatureStoryViewController *dfs = [[DailyFeatureStoryViewController alloc] init];
    dfs.url = url;
    dfs.model = dailyModel;
    dfs.shouChangModel = model;
    
    [self.navigationController pushViewController:dfs animated:YES];
    [dfs release];

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
        if (indexPath.section == 0) {
            
            DBsearchModel *model = _DataBaseArr[indexPath.row];
            
            SearchResultDisplayViewController *searchResult = [[SearchResultDisplayViewController alloc] init];
            
           //去汉子化  拼接成网址
            NSString *searchString = [model.searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *str = @"http://api.breadtrip.com/v2/search/?key=zhanghongguo&sign=f8575338f5797c7992310a6b7c94cdca";
            
            self.urlResult = [str stringByReplacingOccurrencesOfString:@"zhanghongguo" withString:searchString];
            
            
            
            searchResult.url = _urlResult;
            
            [self.navigationController pushViewController:searchResult animated:YES];
            
            [searchResult release];
            
        }else if (indexPath.section == 1){
            
            SearchModel *model = _searchoutCountrYArr[indexPath.row];
            
            CityViewController *city = [[CityViewController alloc] init];
            
            
            //拼接出网址字符串
            NSString *type = [NSString stringWithFormat:@"%@", model.type];
            NSString *tripID = [NSString stringWithFormat:@"%@", model.id];
            
            NSString *url = @"http://api.breadtrip.com/destination/place/2/4087/";
            NSString *url1 = [url stringByReplacingOccurrencesOfString:@"2" withString:type];
            
            NSString *urlResult = [url1 stringByReplacingOccurrencesOfString:@"4087" withString:tripID];
            //推荐地点的网址
            NSString *url2 = @"http://api.breadtrip.com/destination/place/2/4087/pois/all/?start=0&count=20&sort=default&shift=false";
            NSString *resultUrl = [url2 stringByReplacingOccurrencesOfString:@"2" withString:type];
            NSString *resultUrlLast = [resultUrl stringByReplacingOccurrencesOfString:@"4087" withString:tripID];
            
            city.type = type;
            city.spot_id = tripID;
            city.url2 = resultUrlLast;
            city.url = urlResult;
            city.name = model.name_orig;
            [self.navigationController pushViewController:city animated:YES];
            
            [city release];

            
        }else{
            SearchModel *model = _searchInCountryArr[indexPath.row];
            
            CityViewController *city = [[CityViewController alloc] init];
            
            
            //拼接出网址字符串
            NSString *type = [NSString stringWithFormat:@"%@", model.type];
            NSString *tripID = [NSString stringWithFormat:@"%@", model.id];
            
            NSString *url = @"http://api.breadtrip.com/destination/place/2/4087/";
            NSString *url1 = [url stringByReplacingOccurrencesOfString:@"2" withString:type];
            
            NSString *urlResult = [url1 stringByReplacingOccurrencesOfString:@"4087" withString:tripID];
            
            
            //推荐地点的网址
            NSString *url2 = @"http://api.breadtrip.com/destination/place/2/4087/pois/all/?start=0&count=20&sort=default&shift=false";
            NSString *resultUrl = [url2 stringByReplacingOccurrencesOfString:@"2" withString:type];
            NSString *resultUrlLast = [resultUrl stringByReplacingOccurrencesOfString:@"4087" withString:tripID];

            
            
            city.type = type;
            city.spot_id = tripID;
            city.url2 = resultUrlLast;
            city.url = urlResult;
            city.name = model.name_orig;
            [self.navigationController pushViewController:city animated:YES];
            
            [city release];
            
        }
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (_collection == collectionView) {
        return _DailyArr.count;
    }else{
        if (section == 0) {
            if (_DataBaseArr.count > 0) {
                return _DataBaseArr.count;//应该返回一个装搜索记录的数组
            }else{
                return 0;
            }
        }else if (section == 1){
            return _searchoutCountrYArr.count;
        }else{
            return _searchInCountryArr.count;
        }
        
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_collection == collectionView) {
        Daily *model = _DailyArr[indexPath.row];
        
        DailyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DailyCollectionViewCell" forIndexPath:indexPath];
        cell.layer.cornerRadius = 8;
        cell.layer.masksToBounds = YES;
        
        cell.model = model;
        
        return cell;
        
    }else{
        SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SearchCollectionViewCell" forIndexPath:indexPath];
        cell.layer.cornerRadius = 10;
        cell.layer.masksToBounds = YES;
        cell.layer.borderWidth = 1;
        cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
      
        
        if (indexPath.section == 0) {
            
            DBsearchModel *model = _DataBaseArr[indexPath.row];
            if (_DataBaseArr.count > 0) {
                cell.label.text = [NSString stringWithFormat:@"%@", model.searchText];
                
            }else{
                cell.label.text = @"果果";
            }
            
            return cell;
        }else if(indexPath.section == 1){
            SearchModel *model = _searchoutCountrYArr[indexPath.row];
            cell.label.text = model.name_orig;
            return cell;
        }else{
            SearchModel *model = _searchInCountryArr[indexPath.row];
            cell.label.text = model.name_orig;
            return cell;
        }
        
        
        
    }
    
    
}

#pragma mark- UITableView  Delegata & dataSource 方法

//多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _TableView) {
        return _dataArr.count;
    }
    
    return 3;
}
#pragma mark tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row >= 3) {
        Elements *model = _dataArr[indexPath.row - 3];
        NSDictionary *dic = model.data[0];
        if ([model.desc isEqualToString:@"推荐旅行产品"]) {
            self.exprience = [[ExperienceDetailsViewController alloc] init];
            
            [self.navigationController pushViewController:_exprience animated:YES];
            _exprience.url = dic[@"url"];
            
            [_exprience release];
        }else if ([model.desc isEqualToString:@"一个专题"]){
            self.exprience = [[ExperienceDetailsViewController alloc] init];
            
            [self.navigationController pushViewController:_exprience animated:YES];
            _exprience.url = dic[@"url"];
            
    
            
            [_exprience release];
        }else{
            if ([model.type integerValue] == 12) {
                type12ViewController *tyoe = [[type12ViewController alloc] init];
                [self.navigationController pushViewController:tyoe animated:YES];
                [tyoe release];
            }else{
                
                NSDictionary *dic = [model.data firstObject];
                NSNumber *num = dic[@"id"];
                NSString *idStr = [num stringValue];
                
                GameViewController *game = [[GameViewController alloc] init];
                game.tripId = idStr;
                
                game.model = model;
                
                [self.navigationController pushViewController:game animated:YES];
                [game release];
                
            }
            
            
        }
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        if (indexPath.row == 0) {
            DailyFeatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DailyFeatureTableViewCell"];
            //设置代理人
            cell.delegate = self;

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else if (indexPath.row == 1){
            
            DailyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DailyTableViewCell"];
            cell.isWifi = _isWifi;
            //设置代理人
            cell.delegate = self;
            return cell;
        }else if (indexPath.row == 2) {
            RecommendLogoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendLogoTableViewCell"];
            
          
            //取消点击阴影
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            Elements *model = _dataArr[indexPath.row - 3];
            
            if([model.desc isEqualToString:@"推荐旅行产品"] ) {
                
                RecommendProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendProductTableViewCell"];
                cell.model = model;
                NSLog(@"%@", model.desc);
              
                //取消点击阴影
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            } else if ([model.desc isEqualToString:@"一个专题"]) {
                RecommendProductTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RecommendProductTableViewCell"];
                cell.model = model;
                NSLog(@"%@", model.desc);
               
                //取消点击阴影
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }else{
                HotPlaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HotPlaceTableViewCell"];
                //取消点击阴影
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.model = model;
                return cell;
                
            }
        }
}
//分区高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   if (tableView == _TableView) {
        if (indexPath.row == 0) {
            return 50;
        }
        
        if (indexPath.row == 1) {
            return ([UIScreen mainScreen].bounds.size.height / 2 - 80)*2+30;
        }
        if (indexPath.row == 2) {
            return 50;
        }
        return 200;
    }else{
        return 200;
    }
}
- (void)initView{
    self.view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view1.frame.size.width, 200)];
    [self.view addSubview:_view1];
    [_view1 release];
}

/**<  网络状态alert */
- (void)checkNetWorkState {
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    // 2.检测手机能否上网
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    // 有wifi状态
    if ([wifi currentReachabilityStatus] != NotReachable) {
        
        _isWifi = YES;
       
        
        // 手机网络状态
    }else if ([conn currentReachabilityStatus] != NotReachable){
        
        _isWifi = YES;
        
        // 无网络
    }else{
        
        
        _isWifi = NO;
        
        
    }
    
    
}




/** 数据处理 */
- (void)handleData{
    
    if (_isWifi == NO) {
        {
            //从缓存中取
            //sdWebImage的缓存文件路径
            NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
            NSString * path1 = [path stringByAppendingPathComponent:@"Caches"];
            NSString *path2 = [path1 stringByAppendingPathComponent:@"huancun"];
            NSData *data = [NSData dataWithContentsOfFile:path2];
            
            if (data != nil) {
                NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                
            NSDictionary *dataDic = dicResult[@"data"];
                
                
                self.page11 = [NSString stringWithFormat:@"%@", dataDic[@"next_start"]];
                
                //用一个属性数组去接受搜索数据
                
                NSArray *searchArr = dataDic[@"search_data"];
                
                NSArray *OutCountryArr = searchArr[0][@"elements"];
                
                self.searchoutCountrYArr = [SearchModel ModelHandleWithArray:OutCountryArr];
                NSLog(@"%@", _searchoutCountrYArr);
                
                NSArray *InCountryArr = searchArr[1][@"elements"];
                self.searchInCountryArr = [SearchModel ModelHandleWithArray:InCountryArr];
                NSLog(@"%@", _searchInCountryArr);
                
                [_searchCollection reloadData];
                
                
                
                
                
                NSArray *elements = dataDic[@"elements"];
                
                
                
                //初始化每日精选数组
                
                NSMutableArray *arrDaily = [NSMutableArray array];
                
                //初始化数据数组
                
                NSMutableArray *dataArr = [NSMutableArray array];
                
                //初始化数组
                
                NSMutableArray *bannerArr = [NSMutableArray array];
                //遍历数组 进行分类信息
                
                for (NSDictionary *dic  in elements) {
                    
                    if ([dic[@"desc"] isEqualToString:@""]) {
                        
                        [arrDaily addObject:dic];
                        
                    }else if ([dic[@"desc"] isEqualToString:@"广告banner"]){
                        [bannerArr addObject:dic];
                    }else if([dic[@"type"] integerValue] == 4){
                        
                        [dataArr addObject:dic];
                    }
                }
                
                
                
                
                //            KVC赋值
                self.dataArr = [Elements ModelHandleWithArray:dataArr];
                
                
                //将广告对象进行赋值
                NSDictionary *dic11 = [bannerArr firstObject];
                
                NSArray *banArr = dic11[@"data"][0];
                //KVC赋值
                self.BannerArr = [Banner ModelHandleWithArray:banArr];
                
                
                
                //创建一个可变数组  初始化
                NSMutableArray *arrDaily1 = [NSMutableArray array];
                //取出原数组中的两个标题元素
                for (NSDictionary *dic in arrDaily) {
                    
                    if ([dic[@"type"] integerValue] == 10) {
                        [arrDaily1 addObject:dic];
                    }
                    
                }
                
                self.DailyArr = [Daily ModelHandleWithArray:arrDaily1];
                
                
                [self initView];
                _TableView.tableHeaderView = _view1;
                [self initBanner];
                
                [_TableView reloadData];
                
                [GiFHUD dismiss];
            }
                
            }
        
    }
    
        [AFNetWorkingHandle GETRequestWithURLString:@"http://api.breadtrip.com/v2/index/" completionWithSuccess:^(id result) {
            
            
            
            //判断result有没有数据， 有数据就是有网， 没数据就是没网
            if (_isWifi == YES) {
                //用字典去接受结果
                NSDictionary *dic = result;
                //sdWebImage的缓存文件路径
                NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
                NSString * path1 = [path stringByAppendingPathComponent:@"Caches"];
                
                NSString *path2 = [path1 stringByAppendingPathComponent:@"huancun"];
                NSFileManager *manager = [NSFileManager defaultManager];
                NSData *data1 = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
                [manager createFileAtPath:path2 contents:data1 attributes:nil];
               
                BOOL resultScuuess = [data1 writeToFile:path2 atomically:YES];
                if (resultScuuess) {
                    NSLog(@"写入成功");
                }else{
                    NSLog(@"写入失败");
                }
                
                
                {
                    //从缓存中取
                    //sdWebImage的缓存文件路径
                    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
                    NSString * path1 = [path stringByAppendingPathComponent:@"Caches"];
                    NSString *path2 = [path1 stringByAppendingPathComponent:@"huancun"];
                    NSData *data = [NSData dataWithContentsOfFile:path2];
                    NSDictionary *dicResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                    
                    
                    
                    
                    NSDictionary *dataDic = dicResult[@"data"];
                    
                    
                    self.page11 = [NSString stringWithFormat:@"%@", dataDic[@"next_start"]];
                    
                    //用一个属性数组去接受搜索数据
                    
                    NSArray *searchArr = dataDic[@"search_data"];
                    
                    NSArray *OutCountryArr = searchArr[0][@"elements"];
                    
                    self.searchoutCountrYArr = [SearchModel ModelHandleWithArray:OutCountryArr];
                    NSLog(@"%@", _searchoutCountrYArr);
                    
                    NSArray *InCountryArr = searchArr[1][@"elements"];
                    self.searchInCountryArr = [SearchModel ModelHandleWithArray:InCountryArr];
                   
                    
                    [_searchCollection reloadData];
                    
                    
                    
                    
                    
                    NSArray *elements = dataDic[@"elements"];
                    
                    
                    
                    //初始化每日精选数组
                    
                    NSMutableArray *arrDaily = [NSMutableArray array];
                    
                    //初始化数据数组
                    
                    NSMutableArray *dataArr = [NSMutableArray array];
                    
                    //初始化数组
                    
                    NSMutableArray *bannerArr = [NSMutableArray array];
                    //遍历数组 进行分类信息
                    
                    for (NSDictionary *dic  in elements) {
                        
                        if ([dic[@"desc"] isEqualToString:@""]) {
                            
                            [arrDaily addObject:dic];
                            
                        }else if ([dic[@"desc"] isEqualToString:@"广告banner"]){
                            [bannerArr addObject:dic];
                        }else if (!([dic[@"type"] integerValue] == 12)){
                            
                            [dataArr addObject:dic];
                        }
                    }
                    
                    
                    
                    
                    //            KVC赋值
                    self.dataArr = [Elements ModelHandleWithArray:dataArr];
                    
                    //            NSLog(@"%@", _dataArr);
                    
                    
                    //将广告对象进行赋值
                    NSDictionary *dic11 = [bannerArr firstObject];
                    
                    NSArray *banArr = dic11[@"data"][0];
                    //KVC赋值
                    self.BannerArr = [Banner ModelHandleWithArray:banArr];
                    
                    
                    
                    //创建一个可变数组  初始化
                    NSMutableArray *arrDaily1 = [NSMutableArray array];
                    //取出原数组中的两个标题元素
                    for (NSDictionary *dic in arrDaily) {
                        
                        if ([dic[@"type"] integerValue] == 10) {
                            [arrDaily1 addObject:dic];
                        }
                        
                    }
                    
                    self.DailyArr = [Daily ModelHandleWithArray:arrDaily1];
                    
                    
                    [self initView];
                    _TableView.tableHeaderView = _view1;
                    [self initBanner];
                    
                    [_TableView reloadData];
                    
                    [GiFHUD dismiss];
                }
                
                
            }else{
                
            }
            
            
            
            
            
        } withFailure:^(id error) {
            
        }];

    [_TableView headerEndRefreshing];
    [_TableView footerEndRefreshing];
    
}
/** 下拉刷新的数据处理只刷新游记部分 */
- (void)handleDataFoot{
[AFNetWorkingHandle GETRequestWithURLString:_resultUrl completionWithSuccess:^(id result) {
        //用字典去接受结果
        NSDictionary *dic = result;
        NSDictionary *dataDic = dic[@"data"];
        NSArray *elements = dataDic[@"elements"];
        //接受next_start
       self.page11 = [NSString stringWithFormat:@"%@", dataDic[@"next_start"]];
       //临时数组接受
        NSMutableArray *arr = [Elements ModelHandleWithArray:elements];
        
        for (Elements *model in arr) {
            [_dataArr addObject:model];
        }
        
        [_TableView reloadData];
    
          
    } withFailure:^(id error) {
        NSLog(@"%@", error);
        [GiFHUD dismiss];
    }];
    
    
    [_TableView headerEndRefreshing];
    [_TableView footerEndRefreshing];
    
}


/** 网址字符串的去汉化 */
- (void)handleSearchResultData{
    
    NSString *searchString = [_searchTeatID stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *str = @"http://api.breadtrip.com/v2/search/?key=zhanghongguo&sign=f8575338f5797c7992310a6b7c94cdca";
    
    self.urlResult = [str stringByReplacingOccurrencesOfString:@"zhanghongguo" withString:searchString];
    
    [GiFHUD dismiss];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
